package spotGUI.trayIcon;

import java.awt.AWTException;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ResourceBundle;

import javax.swing.ImageIcon;
import javax.swing.JOptionPane;

import managers.messengerManager.FeedbackManager;
import utils.StackTracePrinter;
import utils.UserState;

public class DefaultTrayIconManager implements TrayIconManager {


	private TrayIcon trayIcon = null;
	private SystemTray tray = SystemTray.getSystemTray();

	private FeedbackManager fm;

	private MouseAdapter mouseAdapter = new MouseAdapter() {

		@Override
		public void mouseReleased(MouseEvent e) {
			if (e.getButton() == MouseEvent.BUTTON1) {
				fm.feedbackNotification();
			}
		}
	};

	public DefaultTrayIconManager (FeedbackManager fm) {

		this.fm = fm;

		if (SystemTray.isSupported()) {

			PopupMenu popup = new TrayPopup();
			trayIcon = new TrayIcon(new ImageIcon(fm.getIconPath(UserState.AVAILABLE)).getImage(), UserState.AVAILABLE.getText(), popup);
			trayIcon.setImageAutoSize(true);
			trayIcon.addMouseListener(mouseAdapter);

		} else {
			JOptionPane.showConfirmDialog(null, ResourceBundle.getBundle("spotGUI.trayIcon.messages").getString("DefaultTrayIconManager.notSupported"),
					ResourceBundle.getBundle("spotGUI.trayIcon.messages").getString("DefaultTrayIconManager.notSupported2"), JOptionPane.OK_OPTION, JOptionPane.ERROR_MESSAGE);
			fm.update();
		}
	}

	public void showTrayIcon () {
		try {
			tray.add(trayIcon);
		} catch (AWTException e) {
			StackTracePrinter.print(e);
		}	
	}

	public void hideTrayIcon () {
		tray.remove(trayIcon);
	}

	@Override
	public void updateTrayIconState(UserState state) {
		trayIcon.setImage(new ImageIcon(fm.getIconPath(state)).getImage());
		trayIcon.setToolTip(state.getText());
	}

}
